package cc.customer.system.service.impl;

import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.Utils;
import cc.customer.system.dao.ExConfigMapper;
import cc.customer.system.dao.ExConfigRecordMapper;
import cc.customer.system.domain.ExConfig;
import cc.customer.system.domain.ExConfigRecord;
import cc.customer.system.service.ExModalServices;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ExModalServicesImp  extends BaseService<ExConfigRecord> implements ExModalServices {

    private static final Logger logger= LoggerFactory.getLogger(ExModalServicesImp.class);
    @Autowired
    private ExConfigMapper exConfigMapper;
    @Autowired
    private ExConfigRecordMapper exConfigRecordMapper;

    @Override
    @Transactional
    public ResponseBo exModalAdd(ExConfig exConfig) {
        try {
            /**查询是否存在模板**/
            List<ExConfig> exConfig1 = exConfigMapper.select(exConfig);
            if (!exConfig1.isEmpty()){ return  ResponseBo.error("已经存在"+exConfig.getExCfgName()+"模板"); }
            //不存在模板
            String uuid = Utils.getUUID();
            exConfig.setExCfgUuid(uuid);
            exConfig.setExCfgTime(new Date());
            int num = exConfigMapper.insert(exConfig);
            if (num > 0){
                return ResponseBo.ok(exConfig);
            }
        }catch (Exception e){
            logger.error("增加推广模板失败:"+e.getMessage());
            e.printStackTrace();
        }
        return  ResponseBo.error("增加推广模板失败");
    }
    @Override
    public ResponseBo exModalDel(ExConfig exConfig) {
        try {
            int num  = exConfigMapper.delete(exConfig);//this.delete(uuids);
            if (num>0){
                return ResponseBo.ok("删除成功");
            }
        }catch (Exception e){
            logger.error("删除失败："+e.getMessage());
            e.printStackTrace();
        }
        return ResponseBo.error("删除失败");
    }
    @Override
    public ResponseBo selcetAllExModal(ExConfig config) {
        try {
            Example example = new Example(ExConfig.class);
            example.createCriteria().andEqualTo("exCfgType",config.getExCfgType());
            List<ExConfig> list = exConfigMapper.selectByExample(example);
            return ResponseBo.ok(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseBo.error("获取模板失败");
    }

    @Override
    public ResponseBo selectAllExModalRecords(ExConfigRecord exConfigRecord) {
        try {
            List<ExConfigRecord> list = exConfigRecordMapper.selectAllExModalRecordsByUuid(exConfigRecord.getExCPuuid(),exConfigRecord.getExCType());
            return ResponseBo.ok(list);
        }catch (Exception e){
            logger.error("获取模板得详细信息失败："+e.getMessage());
        }
        return ResponseBo.error("获取失败");
    }

    @Override
    @Transactional
    public ResponseBo editExModalRecords(ExConfigRecord exConfigRecord) {
        try {
            /**定义三个需要操作得集合**/
            List<ExConfigRecord> addlist = new ArrayList<>();//新增
            List<ExConfigRecord> addupdate = new ArrayList<>();//更新
            List<String> adddelt = new ArrayList<>();//删除

            /**1：查询当前模板得配置项目**/
            List<ExConfigRecord> list = exConfigRecordMapper.selectAllExModalRecordsByUuid(exConfigRecord.getExCPuuid(),exConfigRecord.getExCType());
            /**2: 解析配置得模板**/
            String []iduuids = exConfigRecord.getExCUuid().split(","); //uuid 模板
            List<String> uuids = Arrays.asList(iduuids);

            String []deptids = exConfigRecord.getExCDept().split(",");//部门 模板id
            List<String> deptd = Arrays.asList(deptids);

            String []nums = exConfigRecord.getExCNum().split(","); //配置得数量
            List<String> numsid = Arrays.asList(nums);

            String []orders = exConfigRecord.getExCOrder().split(","); //排序
            List<String> order = Arrays.asList(orders);

            String []totles = exConfigRecord.getExCYtotle().split(",");
            List<String> titlesall =  Arrays.asList(totles);

            //比较数据
            Boolean istrue = (uuids.size() == deptd.size());
            Boolean isTure1 = (numsid.size() == order.size());
            Boolean isTreu2 = (uuids.size() == numsid.size());
            Boolean isTreu3 = (uuids.size() == titlesall.size());
            if (!istrue || !isTure1 ||!isTreu2||!isTreu3){
                return ResponseBo.error("获取数据失败");
            }
            //循环数据 判断有没有新模板，有没有删除老模板
            for(int i=0;i<uuids.size();i++){
                String ids  = uuids.get(i);
                //新模板
                if ("1".equals(ids)){
                    //执行插入
                    ExConfigRecord recordadd = new ExConfigRecord();
                    recordadd.setExCDept(deptd.get(i));
                    recordadd.setExCCycles(0);
                    recordadd.setExCNum(numsid.get(i));
                    recordadd.setExCOrder(order.get(i));
                    recordadd.setExCPuuid(exConfigRecord.getExCPuuid());
                    recordadd.setExCTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
                    recordadd.setExCUuid(Utils.getUUID());
                    recordadd.setExCYnum(0);
                    recordadd.setExCYtotle(titlesall.get(i));
                    recordadd.setExCIsdis("0");
                    recordadd.setExCType(exConfigRecord.getExCType());
                    addlist.add(recordadd);
                }else{
                    for (ExConfigRecord e :list){
                        if (e.getExCUuid().equals(ids)){
                            e.setExCNum(numsid.get(i));
                            e.setExCOrder(order.get(i));
                            e.setExCYtotle(titlesall.get(i));
                            addupdate.add(e);
                        }
                    }
                }
            }
            //查询需要删除得模板问题
            for (ExConfigRecord e :list){
                Boolean falg = false;
                for(int j=0;j<uuids.size();j++){
                    String idsuuid = uuids.get(j);
                    if (e.getExCUuid().equals(idsuuid)){
                        falg = true;
                        break;
                    }
                }
                if (!falg){
                    adddelt.add(e.getExCId()+"");
                }
            }
            //执行操作
            logger.info("新增得数目："+addlist.size());
            //新增
            if (!addlist.isEmpty()){
                exConfigRecordMapper.insertList(addlist);
            }
            //更新
            logger.info("更新得数目："+addupdate.size());
            if(!addupdate.isEmpty()){
                exConfigRecordMapper.updateBatchExModalRecords(addupdate,exConfigRecord.getExCType());
            }
            //删除
            logger.info("删除得数目："+adddelt.size());
            if (!adddelt.isEmpty()){
                this.batchDelete(adddelt,"exCId",ExConfigRecord.class);
            }

        }catch (Exception e){
            logger.error("更新推广资源配置失败: "+e.getMessage());
            return ResponseBo.error("保存失败");
        }
        return ResponseBo.ok("保存成功");
    }
}
